package com.yuwen.yuwenRPC.protocol;

/**
 * @ClassNameProtocolMessageEncoder
 * @Description TODO
 * @Author钰玟
 * @Date2025/4/2 下午8:22
 * @Version 1.0
 **/

import com.yuwen.yuwenRPC.serializer.Serializer;
import com.yuwen.yuwenRPC.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/**
 * 协议编码器
 */
public class ProtocolMessageEncoder {

    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        //判断 协议消息(头) 是否为空
        if(protocolMessage==null||protocolMessage.getHeader()==null){
            return Buffer.buffer();
        }

        ProtocolMessage.Header header = protocolMessage.getHeader();
        //依次向缓冲写入字段
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());
        //获取序列化器

        ProtocolMessageSerializerEnum protocolMessageSerializerEnum = ProtocolMessageSerializerEnum.getByKey(header.getSerializer());
        if(protocolMessageSerializerEnum==null){
            throw new RuntimeException("序列化器协议不存在");
        }
        Serializer serializer = SerializerFactory.getSerializer(protocolMessageSerializerEnum.getValue());
        byte[] body = serializer.serialize(protocolMessage.getBody());
        //添加数据
        buffer.appendInt(body.length);
        buffer.appendBytes(body);

        return buffer;
    }


}
